var UserInterface = EventDispatcher.extend({

	SPACE_KEYNUM: 32,
	
	directionKeysRelations: null,
	controlButton: null,
	currentGameState: null,
	
	constructor: function()
	{
		this.currentGameState = GAME_STATE.PAUSED;
		this.directionKeysRelations = {
			37: DIRECTION.LEFT,	
			38: DIRECTION.TOP,
			39: DIRECTION.RIGHT,
			40: DIRECTION.BOTTOM
		};
		this.controlButton = $('#controlButton');
		this.controlButton.bind('click', handler(this, 'onControlButtonClick'));
		window.onkeydown = handler(this, 'keydownHandler');
	},

	setGameState: function(gameState)
	{
		if (gameState == GAME_STATE.GAME_OVER)
		{
			this.controlButton.text('Restart');
		}
		this.currentGameState = gameState;
	},
	
	changeGameState: function()
	{
		switch (this.currentGameState)
		{
		case GAME_STATE.PAUSED:
			this.setGameState(GAME_STATE.PLAYING);
			this.controlButton.text('Pause');
			break;
		case GAME_STATE.PLAYING:
		case GAME_STATE.RESTART:
			this.setGameState(GAME_STATE.PAUSED);
			this.controlButton.text('Resume');
			break;
		case GAME_STATE.GAME_OVER:
			this.setGameState(GAME_STATE.RESTART);
			this.controlButton.text('Pause');
			break;
		}
		this.dispatchEvent(UserInterface.GAME_STATE_CHANGE, this.currentGameState);
	},
	
	onControlButtonClick: function()
	{
		this.changeGameState();
	},
	
	keydownHandler: function(evt)
	{
		var keyNum = evt.which;
		if (this.isControlKeyNum(keyNum) && 
			((this.currentGameState == GAME_STATE.PLAYING)
			|| (this.currentGameState == GAME_STATE.RESTART)))
		{
			evt.preventDefault();
			var direction = this.getDirectionFromKeyNum(keyNum);
			this.dispatchEvent(UserInterface.DIRECTION_CHANGE, direction);
		}
		else if (keyNum == this.SPACE_KEYNUM)
		{
			evt.preventDefault();
			this.changeGameState();
		}
	},

	isControlKeyNum: function(keyNum)
	{
		return this.directionKeysRelations[keyNum] != undefined;
	},
	
	getDirectionFromKeyNum: function(keyNum)
	{
		return this.directionKeysRelations[keyNum];
	}
}, {
	DIRECTION_CHANGE: 'directionChange',
	GAME_STATE_CHANGE: 'gameStateChange'
});